/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
import webUni from "@/common/uni.webview.js"
import wx from 'jweixin-module'
const tui = {
	//接口地址
	interfaceUrl: function() {
		return 'https://kduimi.zzcyx1688.cn/data/' //接口
	},
	faceUrl: function() {
		return 'https://chenyx.zzcyx1688.cn/kduilai/' //h5域名
	},
	loginUrl:function(){
		return 'https://chenyx.zzcyx1688.cn/login/' //公共登录
	},
	appid:function(){
		return 'wxecac9a65b748e197'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text ,
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// console.log(url)
		// uni.setStorageSync("d_token", 'b684810cd396cec47ddc18bf45e914d4')
		// uni.setStorageSync("d_token", '2f340d0380aae9e0ca95bd66a39a1609')
		postData.equipment_type = 2
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					// 'content-Type': 'application/json',
					'content-type':'application/x-www-form-urlencoded',
					'authorization': tui.getToken(),
					// 'equipment-type':2,
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==1){
						resolve(res.data)
					} else if (res.data.code ==401) {
						uni.removeStorage({
						    key: 'd_token',
						    success: function (res) {
						        console.log('success');
						    }
						});
						uni.removeStorage({
						    key: 'refCode',
						    success: function (res) {
						        console.log('success');
						    }
						});
						let local = location.href;
						let urls = local.split('?')[0]
						uni.setStorageSync('d_url', local)
						uni.$emit("isbtn",true)
						// tui.wetLogin()
						tui.toast('登录失效,请重新登录')
						setTimeout(function(){
							window.location.href = tui.loginUrl()+'#/pages/login/login?url='+tui.faceUrl()+'#/'+"&inviter_code="+uni.getStorageSync('refCode')
						},1000)
						return
					}else if (res.data.code==407){
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						setTimeout(function(){
							webUni.navigateTo({
								url: '/pages/MyOrderList/MyOrderList?type=0'
							})
						},1000)
					}else{
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						if(res.data.info=="收款方式不能为空"){
							setTimeout(function(){
								tui.href('/pages/bank/bank_list_1')
							},1000)
						}
						if(res.data.info=="请先完善个人信息"){
							setTimeout(function(){
								tui.href('/pages/AddressEdit/AddressEdit?type=2')
							},1000)
						}
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					reject(res)
				}
			})
		})
	},
	addrequest: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// console.log(url)
		// uni.setStorageSync("d_token", 'cfd8a719c4fe5b0dc98a8cb5e53f454a')
		// uni.setStorageSync("d_token", '2f340d0380aae9e0ca95bd66a39a1609')
		postData.equipment_type = 2
		return new Promise((resolve, reject) => {
			uni.request({
				// url: "/api/" + url,
				url:'https://live-shop.zzcyx1688.cn/' + url,
				data: postData,
				header: {
					// 'content-Type': 'application/json',
					'content-type':'application/json',
					'Authorization': tui.getToken(),
					"Project-Name":"live34",
					"Equipment-Type":"2",
					"System-Type":'php_system'
					// 'equipment-type':2,
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==1){
						resolve(res.data)
					} else if (res.data.code ==401) {
						uni.removeStorage({
						    key: 'd_token',
						    success: function (res) {
						        console.log('success');
						    }
						});
						uni.removeStorage({
						    key: 'refCode',
						    success: function (res) {
						        console.log('success');
						    }
						});
						let local = location.href;
						let urls = local.split('?')[0]
						uni.setStorageSync('d_url', local)
						uni.$emit("isbtn",true)
						// tui.wetLogin()
						tui.toast('登录失效,请重新登录')
						setTimeout(function(){
							window.location.href = tui.loginUrl()+'#/pages/login/login?url='+tui.faceUrl()+'#/'+"&inviter_code="+uni.getStorageSync('refCode')
						},1000)
						return
					}else if (res.data.code==407){
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						setTimeout(function(){
							tui.href('/pages/MyOrderList/MyOrderList?type=0')
						},1000)
					}else{
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						if(res.data.info=="收款方式不能为空"){
							setTimeout(function(){
								tui.href('/pages/bank/bank_list_1')
							},1000)
						}
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		let that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'authorization':  tui.getToken(),
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					console.log(d)
					let fileObj = d;
					resolve(fileObj)
				},
				fail: function(res) {
					reject(res)
					that.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile,token) {
		//uni.setStorageSync("thorui_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("d_token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("d_token") ? true : false
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !tui.isLogin()) {
			webUni.navigateTo({
				url: '/pages/common/login/login'
			})
		} else {
			webUni.navigateTo({
				url: url
			});
		}
	},
	
	getRoomSwitch(e){
		let that = this
		tui.request("api.config/getMergeConfig", "POST", {}, false, false, true).then((res) => {
			if(res.code==1){
				// uni.setStorageSync('room_switch', res.data.room_switch)
				uni.setStorageSync('datas_switch', res.data)
			}
		}).catch((res) => {
		
		})
	},
	dianji(fn) {
	    let that = this;
		let is_true = getApp().globalData.is_true
		console.log(is_true)
	    if (is_true) {
	        getApp().globalData.is_true = false;
	        setTimeout(function () {
	            getApp().globalData.is_true = true;
	        }, 5000)
			fn();
	    } else {
	        //如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
	        console.log("请稍后点击")
	    }
	},
	wetLogin(e,d){
		let that = this
		// #ifdef H5
		let urls =tui.faceUrl()+ "#/pages/login/login"
		let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=`+tui.appid()+`&redirect_uri=`+encodeURIComponent(urls)+`&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
		window.location.href = url
		// #endif
		// #ifdef MP
		uni.login({
			provider: 'weixin',
			success: (res) => {
				let data = {code: res.code,inviter_code:uni.getStorageSync('refCode'),openid_inviter_code:uni.getStorageSync('share_openid')}
				tui.request("api.wxapp/session", "POST", data, false, false, true).then((res) => {
					console.log(res)
					tui.toast(res.info)
					uni.removeStorage({
					    key: 'refCode',
					    success: function (res) {
					        console.log('success');
					    }
					});
					uni.setStorageSync('d_token', res.data.token)
					uni.setStorageSync('headimg', res.data.headimg)
					uni.setStorageSync('inviter_code', res.data.inviter_code)
					uni.$emit("isLogin",1)
					if(res.data.is_avatar==2){
						console.log(res.data.is_avatar)
						uni.$emit("isShow",res.data.is_avatar)
					}
					if(e==1){
						tui.getList(d)
					}
				}).catch((res) => {
					that.is_btn = false
				})
			},
		});
		// #endif
		
	},
	wechatLogiNew(e){
		let that = this
		tui.request("api.wechat/wechatLogiNew", "POST", e, false, false, true).then((res) => {
			console.log(res)
			if(res.code==1){
				uni.setStorageSync('d_token', res.data.token)
				uni.setStorageSync('inviter_code', res.data.inviter_code)
				if(uni.getStorageSync('zhiboid')){
					tui.getList(uni.getStorageSync('zhiboid'),1)
					setTimeout(function(){
						uni.setStorageSync('zhiboid','')
					},1000)
				}else if(uni.getStorageSync('shopId')){
					tui.href('/pages/GoodsDetails/GoodsDetails?id='+uni.getStorageSync('shopId'))
					setTimeout(function(){
						uni.setStorageSync('shopId','')
					},1000)
				}else if(uni.getStorageSync('d_url')){
					window.location.href =uni.getStorageSync('d_url')
					setTimeout(function(){
						uni.setStorageSync('d_url','')
					},1000)
				}else{
					uni.switchTab({
						url:'/pages/home/home?inviter_code='+res.data.inviter_code
					})
				}
			}
		}).catch((res) => {
			
		})
	},
	TongjiLive(e,d){
		let that = this
		console.log(e,d+"qweqweqweqweqe")
		let equipment = ''
		uni.getSystemInfo({
		    success: function (res) {
		        console.log(res);
				equipment = res.system
		    }
		});
		if(d==0){
			return
		}
		return
		tui.request("api.auth.live/lookLive", "POST", {type:e,room_id:d,equipment:equipment}, false, false, true).then((res) => {
			console.log(res)
			if(res.code==1){
				uni.setStorageSync('lookLive', e)
			}
		}).catch((res) => {
			
		})
	},
	zhiboList: function() {
		let that = this
		tui.request("api.auth.live/liveRoomV2", "POST", {page:1}, false, false, true).then((res) => {
			if(res.code==1){
				if(res.data.list.length==0){
					// uni.setStorageSync('iszhibo',false)
					uni.$emit("fcNotic",false)
				}else{
					// uni.setStorageSync('iszhibo',true)
					uni.$emit("fcNotic",true)
					uni.setStorageSync('zhiStatu',res.data.list[0])
				}
			}
		}).catch((res) => {
			
		})
	},
	getList(e,d){
		let that = this
		tui.request("api.auth.live/liveRoomV2", "POST", {page:1}, false, false, true).then((res) => {
			if(res.code==1){
				if(res.data.list){
					res.data.list.map((item,index)=>{
						if(e==item.id){
							uni.setStorageSync('zhiboStatus',item)
							if(d==1){
								tui.href('/pages/zhibo/zhibo?zhiboid='+item.id+"&inviter_code="+uni.getStorageSync('inviter_code')+"&yaoqing="+uni.getStorageSync('refCode'))
							}else{
								window.location.href =tui.faceUrl()+'#/pages/zhibo/zhibo?zhiboid='+item.id+"&inviter_code="+uni.getStorageSync('inviter_code')+"&yaoqing="+uni.getStorageSync('refCode')
							}
							
						}
					})
				}else{
					if(d==2){
						window.location.href =tui.faceUrl()+'#/pages/home/home'
					}
				}
			}
		}).catch((res) => {
			
		})
	},
	phoneYin(phone){
		if(phone){
			return  phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
	},
	phoneMore(phone){
		var arr = phone.split(',')
		var data =''
		arr.map((item,index)=>{
			data = data+item.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')+','
		})
		data = data.slice(0, -2)
		if(phone){
			return  data;
		}
	},
	getBindcode(){
		let that = this
		tui.request("api.auth.live/blindInfo", "POST", {}, false, false, true).then((res) => {
			if(res.code==1){
				if(res.data.pid0==0){
					if(res.data.inviter_code_arr.indexOf(uni.getStorageSync('refCode'))!=-1){
						tui.request("api.auth.live/invBlind", "POST", {inviter_code:uni.getStorageSync('refCode')}, false, false, true).then((res) => {
							if(res.code==1){
								uni.removeStorage({
								    key: 'refCode',
								    success: function (res) {
								        console.log('success');
								    }
								});
							}
						}).catch((res) => {
							
						})
					}
				}
			}
		}).catch((res) => {
		
		})
	},
	setIncrement(val) {
	    let status = false,
	    step = 3.30* val / (1000 / 30),
	    count  = 0,
	    interval = null;
	    interval = setInterval(() => {
	        if(count < val) {
	            count = count + step;
	        } else {
	            status = true
				count = val
	        }
	        if(status) {
	            clearInterval(interval)
	        }
			return count
	    }, 30)
		
	},
	secondsToTime(seconds) {
	  const hours = Math.floor(seconds / 3600);
	  const minutes = Math.floor((seconds % 3600) / 60);
	  const remainingSeconds = seconds % 60;
	  return hours + "时" + minutes + "分" + remainingSeconds + "秒" ;
	},
	autoUpdate() { //更新新版本
	  	var self = this
	  	// 获取小程序更新机制兼容
	  	console.log('canUndate',uni.canIUse('getUpdateManager'))
	  	if (uni.canIUse('getUpdateManager')) {
	  		const updateManager = uni.getUpdateManager()
	  		//1. 检查小程序是否有新版本发布
	  		updateManager.onCheckForUpdate(function(res) {
	  			// 请求完新版本信息的回调
	  			console.log('hasUpdate',res.hasUpdate)
	  			if (res.hasUpdate) {
	  				//检测到新版本，需要更新，给出提示
	  				uni.showModal({
	  					title: '更新提示',
	  					content: '检测到新版本，是否下载新版本并重启小程序？',
	  					success: function(res) {
	  						if (res.confirm) {
	  							//2. 用户确定下载更新小程序，小程序下载及更新静默进行
	  							self.downLoadAndUpdate(updateManager)
	  						} else if (res.cancel) {
	  							//用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
	  							uni.showModal({
	  								title: '温馨提示~',
	  								content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
	  								showCancel: false, //隐藏取消按钮
	  								confirmText: "确定更新", //只保留确定更新按钮
	  								success: function(res) {
	  									if (res.confirm) {
	  										//下载新版本，并重新应用
	  										self.downLoadAndUpdate(updateManager)
	  									}
	  								}
	  							})
	  						}
	  					}
	  				})
	  			}
	  		})
	  	} else {
	  		// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
	  		uni.showModal({
	  			title: '提示',
	  			content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
	  		})
	  	}
	  },
	  /**
	   * 下载小程序新版本并重启应用
	   */
	  downLoadAndUpdate(updateManager) {
	  	var self = this
	  	uni.showLoading();
	  	//静默下载更新小程序新版本
	  	updateManager.onUpdateReady(function() {
	  		uni.hideLoading()
	  		//新的版本已经下载好，调用 applyUpdate 应用新版本并重启
	  		updateManager.applyUpdate()
	  	})
	  	updateManager.onUpdateFailed(function() {
	  		// 新的版本下载失败
	  		uni.showModal({
	  			title: '已经有新版本了哟~',
	  			content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
	  		})
	  	})
	  },
	  wxReady(res,e,d) {
		let url =''
		if(e==1){
			res = uni.getStorageSync('shareZhibo')
			url = tui.faceUrl()+'#/pages/home/home?inviter_code='+uni.getStorageSync('inviter_code')+'&zhiboid='+d  //直播间
		}else if(e==2){
			res = uni.getStorageSync('shareShop')
			url = tui.faceUrl()+'#/pages/home/home?inviter_code='+uni.getStorageSync('inviter_code')+'&shopId='+d  //商品详情
		}else{
			url = tui.faceUrl()+'#/pages/home/home?inviter_code='+uni.getStorageSync('inviter_code')
		}
	  	wx.ready(function() {
	  		
	  		wx.onMenuShareAppMessage({
	  			title: res.title, // 分享标题  
	  			desc: res.desc, // 分享描述  
	  			link: url, // 分享链接  
	  			imgUrl: res.share_img, // 分享图标
	  			success: res => {
	  				// 用户确认分享后执行的回调函数
	  				console.log(res)
	  				console.log('分享成功')
					uni.removeStorage({
					    key: 'shareUrl',
					    success: function (res) {
					        console.log('success');
					    }
					});
	  			},  
	  			cancel: res => {
	  				// 用户取消分享后执行的回调函数
	  				console.log(res)
	  				console.log('bbbbbbb')
					uni.removeStorage({
					    key: 'shareUrl',
					    success: function (res) {
					        console.log('success');
					    }
					});
	  			},
	  			fail: res => {
	  				console.log(res)
	  				console.log('cccccc')
	  			}
	  		});
	  		wx.onMenuShareTimeline({
	  			title: res.title, // 分享标题
	  			link:url, // 分享链接  
	  			imgUrl: res.share_img, // 分享图标
	  			success: res => {
	  				// 用户确认分享后执行的回调函数
	  				console.log(res)
	  				console.log('分享成功')
					uni.removeStorage({
					    key: 'shareUrl',
					    success: function (res) {
					        console.log('success');
					    }
					});
	  			},  
	  			cancel: res => {
	  				// 用户取消分享后执行的回调函数
	  				console.log(res)
	  				console.log('bbbbbbb')
					uni.removeStorage({
					    key: 'shareUrl',
					    success: function (res) {
					        console.log('success');
					    }
					});
	  			},
	  			fail: res => {
	  				console.log(res)
	  				console.log('cccccc')
	  			}
	  		});
	  		
	  	});
	  },
	  isValidPhoneNumber(phoneNumber) {
	      return /^1[3456789]\d{9}$/.test(phoneNumber);
	  },
	  wxShare(e,d) {
	  	let that = this
	  	var surl = location.href.split('#')[0]; //据说可以解决URL中带参数的问题，前台用的js编码，后台解码
		let res = uni.getStorageSync('datas_switch')
		wx.config({
		  debug: false, // 是否开启调试模式
		  appId: res.scan.info.appId, // 必填，公众号的唯一标识
		  timestamp: res.scan.info.timestamp, // 必填，生成签名的时间戳
		  nonceStr: res.scan.info.nonceStr, // 必填，生成签名的随机串
		  signature: res.scan.info.signature, // 必填，签名，见附录1
		  jsApiList: res.scan.info.jsApiList
		})
		tui.wxReady(res.scan,e,d)
		return
	  	tui.request("api.auth.live/scan", "POST", {url:surl}, false, false, true).then((res) => {
	  		console.log(res)
	  		if(res.code==1){
	  			wx.config({
	  			  debug: false, // 是否开启调试模式
	  			  appId: res.data.info.appId, // 必填，公众号的唯一标识
	  			  timestamp: res.data.info.timestamp, // 必填，生成签名的时间戳
	  			  nonceStr: res.data.info.nonceStr, // 必填，生成签名的随机串
	  			  signature: res.data.info.signature, // 必填，签名，见附录1
	  			  jsApiList: res.data.info.jsApiList
	  			})
	  			tui.wxReady(res.data,e,d)
	  		}
	  	}).catch((res) => {
	  		
	  	})
	  	
	  },
}

export default tui